package com.ttdevs.ttrss;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import com.sun.syndication.feed.synd.SyndCategory;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.ttdevs.ttrss.bean.Article;
import com.ttdevs.ttrss.parse.DomParser;
import com.ttdevs.ttrss.parse.SaxParser;
import com.ttdevs.ttrss.ui.CustomActivity;
import com.ttdevs.ttrss.util.TtLog;

public class MainActivity extends Activity implements OnClickListener {
	private final static String PARSERRESULT = "parser_result";
	private ListView listView;

	private ProgressDialog progressDialog;
	private Spinner urlSpinner;
	private String rssSource;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			@SuppressWarnings("unchecked")
			List<Article> articlesList = (List<Article>) msg.getData().get(PARSERRESULT);
			StringBuilder resultSB = new StringBuilder();
			int i = 0;
			for (Article article : articlesList) {
				resultSB.append(++i + ".");
				resultSB.append(article.getTitle());
				resultSB.append('\n');
			}
			listArticle(articlesList);
			stopProsessBar();
			TtLog.d("Click SAX View:" + System.currentTimeMillis());
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		findViewById(R.id.sax).setOnClickListener(this);
		findViewById(R.id.clear).setOnClickListener(this);
		urlSpinner = (Spinner) findViewById(R.id.rss_source);
		listView = (ListView) findViewById(R.id.listview);
		System.out.println(System.currentTimeMillis() + "aa");
	}

	@Override
	public void onClick(View v) {
		rssSource = urlSpinner.getSelectedItem().toString();
		switch (v.getId()) {
		case R.id.sax:
			TtLog.d("start...");
			startProsessBar();
			// new Thread(saxParse, "sax").start();
			new Thread(domParse, "dom").start();
			break;
		case R.id.clear:
			TtLog.d("Clear cache...");
			// startActivity(new Intent(this, ArticleView.class));
			new Thread(new Runnable() {

				@Override
				public void run() {
					parseRss();
				}
			}).start();
			break;
		case R.id.sliding:
			startActivity(new Intent(this, CustomActivity.class));
			break;
		default:
			break;
		}

	}

	public void parseRss() {

		String rss = "http://mobile.csdn.net/rss_mobile.html";
		// rss = "http://www.cnbeta.com/backend.php";

		try {
			SyndFeedInput in = new SyndFeedInput();
			
			// InputStream resource = new URLConn().getResult(rss);
			// SyndFeed feed = in.build(new InputStreamReader(resource));
			XmlReader reader = new XmlReader(new URL(rss));
			SyndFeed feed = in.build(reader);
			
			feed.getAuthor();
			List<SyndEntry> entries = feed.getEntries();
			for (SyndEntry entry : entries) {
				// 标题、连接地址、标题简介、时间是一个Rss源项最基本的组成部分
				System.out.println("标题：" + entry.getTitle());
				System.out.println("连接地址：" + entry.getLink());
				SyndContent description = entry.getDescription();
				System.out.println("标题简介：" + description.getValue());
				System.out.println("发布时间：" + entry.getPublishedDate());

				// 以下是Rss源可先的几个部分
				System.out.println("标题的作者：" + entry.getAuthor());

				// 此标题所属的范畴
				List categoryList = entry.getCategories();
				if (categoryList != null) {
					for (int m = 0; m < categoryList.size(); m++) {
						SyndCategory category = (SyndCategory) categoryList.get(m);
						System.out.println("此标题所属的范畴：" + category.getName());
					}
				}

				// 得到流媒体播放文件的信息列表
				List enclosureList = entry.getEnclosures();
				if (enclosureList != null) {
					for (int n = 0; n < enclosureList.size(); n++) {
						SyndEnclosure enclosure = (SyndEnclosure) enclosureList.get(n);
						System.out.println("流媒体播放文件：" + entry.getEnclosures());
					}
				}
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	Runnable saxParse = new Runnable() {

		@Override
		public void run() {
			try {
				List<Article> articlesList = new SaxParser().parse(rssSource);
				sendMessage(handler, articlesList);
			} catch (IOException e) {
				TtLog.d("IO error");
				e.printStackTrace();
			} catch (Exception e) {
				TtLog.d("parse error");
				e.printStackTrace();
			}

		}
	};

	Runnable domParse = new Runnable() {

		@Override
		public void run() {
			try {
				List<Article> articlesList = new DomParser().parse(rssSource);
				sendMessage(handler, articlesList);
			} catch (IOException e) {
				TtLog.d("IO error");
				e.printStackTrace();
			} catch (Exception e) {
				TtLog.d("parse error");
				e.printStackTrace();
			}

		}
	};

	private void listArticle(List<Article> articlesList) {
		String[] mFrom = new String[] { "title", "description", "author", "pubdate" };
		int[] mTo = new int[] { R.id.title, R.id.description, R.id.author, R.id.pubdate };
		List<Map<String, Object>> listMaps = new ArrayList<Map<String, Object>>();
		Iterator<Article> iterator = articlesList.iterator();
		while (iterator.hasNext()) {
			Article article = iterator.next();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("title", article.getTitle());
			map.put("description", getDescription(article.getDescription()));
			map.put("author", article.getAuthor());
			map.put("pubdate", article.getPubDate());
			map.put("link", article.getLink());
			listMaps.add(map);
			article = null;
		}

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, listMaps, R.layout.article_item_l, mFrom, mTo);
		listView.setAdapter(simpleAdapter);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView.setOnItemClickListener(itemClick);

	}

	private Spanned getDescription(String description) {
		Spanned spanned = Html.fromHtml(description, new ImageGetter() {
			@Override
			public Drawable getDrawable(String source) {
				Log.d("TAG", source);
				// Drawable drawable = null;
				// source = getFilesDir() + "/ic_launcher.png";
				// drawable = Drawable.createFromPath(source); // 显示本地图片
				// drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				// drawable.getIntrinsicHeight());
				// int id = Integer.parseInt(source);
				int id = R.drawable.ic_img;
				Drawable drawable = getResources().getDrawable(id);
				drawable.setBounds(0, 0, 20, 20);
				return drawable;
			}
		}, new TagHandler() {

			@Override
			public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
				Log.d("TAGgatgaga", tag);

			}
		});

		return spanned;
	}

	OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			// AdapterView<?> parent, View view, int position, long id
			HashMap<String, Object> map = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
			TtLog.d(map.get("link").toString());

			Intent intent = new Intent();
			intent.putExtra("URL", map.get("link").toString());
			intent.setClass(MainActivity.this, ArticleView.class);
			// intent.setAction(Intent.ACTION_VIEW);
			// intent.setData(Uri.parse(map.get("link").toString()));
			startActivity(intent);

		}
	};

	/**
	 * send message,此处可能涉及序列化的问题
	 * 
	 * @param handler
	 * @param obj
	 */
	@SuppressWarnings("unchecked")
	private void sendMessage(Handler handler, Object obj) {
		Message msg = new Message();
		Bundle bundleData = msg.getData();
		bundleData.putParcelableArrayList(PARSERRESULT, (ArrayList<? extends Parcelable>) obj);
		msg.setData(bundleData);
		handler.sendMessage(msg);
	}

	private void startProsessBar() {
		// 启动进度条
		if (progressDialog == null || !progressDialog.isShowing()) {
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setCancelable(true);
			progressDialog.setMessage("正在奋力的拉取数据...");
			progressDialog.setProgressStyle(android.R.style.TextAppearance_Holo);
			progressDialog.show();
		}
	}

	private void stopProsessBar() {
		// 启动进度条
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}

	private void startAddRSSSource() {
		LayoutInflater factory = LayoutInflater.from(this);
		final View addRssSourceView = factory.inflate(R.layout.dialog_addrss, null);
		final EditText urlEditText = (EditText) addRssSourceView.findViewById(R.id.rssurl);
		final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this).setIconAttribute(android.R.attr.alertDialogIcon)
				.setTitle("添加RSS源").setView(addRssSourceView).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				}).setPositiveButton("拉取", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String url = urlEditText.getText().toString();
						TtLog.d(url);
					}
				}).setNeutralButton("添加", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

					}
				});
		TtLog.d("显示对话框");
		builder.create();
	}
}
